import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Hero} from '../hero';
import {from, Observable, Subject} from 'rxjs';
import {HeroService} from '../services/hero.service';
import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';

@Component({
  selector: 'app-hero-search',
  templateUrl: './hero-search.component.html',
  styleUrls: ['./hero-search.component.css']
})
export class HeroSearchComponent implements OnInit {

  heros$: Observable<Hero[]>;

  @Output() onVoted = new EventEmitter<Boolean>();
  voted = false;
  _filed1: string;

  @Input()
  set childFiled(filed1: string) {
    this._filed1 = filed1 + ' FF';
  }

  vote(agree: boolean) {
    // const interval = window.setInterval((v) => {
    //   console.log(v);
    // }, 1000, 'arg1', 'arg2');
    //
    // window.setTimeout(() => {
    //   console.log(interval);
    //   window.clearInterval(interval);
    // }, 5000);
    //
    const messages = ['mess1', 'mess2', 'mess3', 'mess4', 'mess5'];
    //
    const stringObservable = from(messages);

    const myObserver = {
      next: x => console.log('oberser got a value : ' + x),
      error: err => console.log('error'),
      complete: () => console.log('complete....')
    };

    // const myObserver2 = {
    //   next: x => console.log('oberser2 got a value : ' + x),
    //   error: err => console.log('error2'),
    //   complete: () => console.log('complete2....')
    // };
    //
    stringObservable.subscribe(myObserver);
    //
    // stringObservable.subscribe(myObserver2);
    //
    //
    // let observable = new Observable((observer) => {
    //   observer.next(111);
    //   observer.next(222);
    //   observer.next(333);
    //   observer.next(444);
    //   observer.next(555);
    //   observer.next(6666);
    // });
    //
    //
    // observable.subscribe(next => {
    //   console.log(next);
    // });
    this.onVoted.emit(agree);
    this.voted = true;
  }


  private searchTerms = new Subject<string>();

  constructor(private heroService: HeroService) {
  }

  ngOnInit() {
    this.heros$ = this.searchTerms.pipe(
      debounceTime(3000),

      distinctUntilChanged(),
      switchMap((term: string) => this.heroService.searchHeros(term))
    );
  }

  search(term: string): void {
    this.searchTerms.next(term);
  }


}
